﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace 蓝牙注册工具.View
{
    /// <summary>
    /// ConfigView.xaml 的交互逻辑
    /// </summary>
    public partial class ConfigView : UserControl
    {
        public ViewModel.ConfigViewModel viewModel = new ViewModel.ConfigViewModel();
        public ConfigView()
        {
            InitializeComponent();
            DataContext = viewModel;
            viewModel.Ports = BLL.PortBLL.GetPorts();
            viewModel.BtPort = MainWindow.config.BtPortname;
            viewModel.ScanDelay = MainWindow.config.ScanDelay;
            viewModel.dBm = MainWindow.config.dBm;
            viewModel.Port1 = MainWindow.config.Channel1Portname;
            viewModel.Port2 = MainWindow.config.Channel2Portname;
            viewModel.Port3 = MainWindow.config.Channel3Portname;
            viewModel.Port4 = MainWindow.config.Channel4Portname;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            List<string> list = new List<string>() { viewModel.Port1, viewModel.Port2, viewModel.Port3, viewModel.Port4, viewModel.BtPort };
            if (list.Count(it => it == viewModel.Port1) > 1 ||
                list.Count(it => it == viewModel.Port2) > 1 ||
                list.Count(it => it == viewModel.Port3) > 1 ||
                list.Count(it => it == viewModel.Port4) > 1 ||
                list.Count(it => it == viewModel.BtPort) > 1)
            {
                HandyControl.Controls.MessageBox.Error("串口冲突");
                return;
            }
            MainWindow.config.BtPortname = viewModel.BtPort;
            MainWindow.config.dBm = viewModel.dBm;
            MainWindow.config.ScanDelay = viewModel.ScanDelay;
            MainWindow.config.Channel1Portname = viewModel.Port1;
            MainWindow.config.Channel2Portname = viewModel.Port2;
            MainWindow.config.Channel3Portname = viewModel.Port3;
            MainWindow.config.Channel4Portname = viewModel.Port4;
            BLL.ConfigBLL.SaveConfigModel();

            BLL.PortBLL.serialPort1.Close();
            BLL.PortBLL.serialPort2.Close();
            BLL.PortBLL.serialPort3.Close();
            BLL.PortBLL.serialPort4.Close();
            BLL.PortBLL.serialPortBt.Close();

        }

        private void ComboBox_DropDownOpened(object sender, EventArgs e)
        {
            viewModel.Ports = BLL.PortBLL.GetPorts();
        }
    }
}
